package net.sudot.chess.business.wechat.api;

import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceHttpClientImpl;
import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfOnlineList;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpSession;

/**
 * 微信操作服务
 *
 * @author tangjialin on 2018-03-10
 */
public class WechatApiService extends WxMpServiceHttpClientImpl implements WxMpService {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    public boolean hasKefuOnline() {
        try {
            WxMpKfOnlineList kfOnlineList = this.getKefuService().kfOnlineList();
            return kfOnlineList != null && kfOnlineList.getKfOnlineList().size() > 0;
        } catch (Exception e) {
            this.logger.error("获取客服在线状态异常:{}", e.getMessage(), e);
        }

        return false;
    }

    public WxMpOAuth2AccessToken getUserToken(HttpSession session) {
        return (WxMpOAuth2AccessToken) session.getAttribute(WxMpOAuth2AccessToken.class.getSimpleName());
    }

    /**
     * FreeMark模版页面中可以这样获取OpenId ${Session['WxMpOAuth2AccessToken'].openId}
     *
     * @param session HttpSession
     * @param token   Token信息
     */
    public void setUserToken(HttpSession session, WxMpOAuth2AccessToken token) {
        session.setAttribute(WxMpOAuth2AccessToken.class.getSimpleName(), token);
    }

}
